#include "HelloWorldScene.h"
#include "SimpleAudioEngine.h"

void setPackageName(const char *packageName);

USING_NS_CC;


Scene *HelloWorld::createScene() {
    return HelloWorld::create();
}

// on "init" you need to initialize your instance
bool HelloWorld::init() {
    //////////////////////////////
    // 1. super init first
    if (!Scene::init()) {
        return false;
    }

    auto visibleSize = Director::getInstance()->getVisibleSize();
    Vec2 origin = Director::getInstance()->getVisibleOrigin();

    /////////////////////////////
    // 2. add a menu item with "X" image, which is clicked to quit the program
    //    you may modify it.

    // add a "close" icon to exit the progress. it's an autorelease object
    auto closeItem = MenuItemImage::create(
            "CloseNormal.png",
            "CloseSelected.png",
            CC_CALLBACK_1(HelloWorld::menuCloseCallback, this));

    closeItem->setPosition(
            Vec2(origin.x + visibleSize.width - closeItem->getContentSize().width / 2,
                 origin.y + closeItem->getContentSize().height / 2));

    // create menu, it's an autorelease object
    auto menu = Menu::create(closeItem, NULL);
    menu->setPosition(Vec2::ZERO);
    this->addChild(menu, 1);

    /////////////////////////////
    // 3. add your codes below...
    // add a label shows "Hello World"
    // create and initialize a label
    auto label = Label::createWithTTF("XiGuSdk Test Demo", "fonts/Marker Felt.ttf", 24);
    // position the label on the center of the screen
    label->setPosition(Vec2(origin.x + visibleSize.width / 2,
                            origin.y + visibleSize.height - label->getContentSize().height));

    // add the label as a child to this layer
    this->addChild(label, 1);

    // add "HelloWorld" splash screen"
    //  auto sprite = Sprite::create("HelloWorld.png");

    // position the sprite on the center of the screen
    //   sprite->setPosition(Vec2(visibleSize.width/2 + origin.x, visibleSize.height/2 + origin.y));

    // add the sprite as a child to this layer
    // this->addChild(sprite, 0);

    //添加文字按钮
    CCMenuItemFont::setFontSize(48);    //设置字号
    CCMenuItemFont::setFontName("Marker Felt"); //设置字体

    CCMenuItemFont *initItem = CCMenuItemFont::create("init", this, menu_selector(
            HelloWorld::initCallback));//添加文字按钮，点击实现缩放
    initItem->setColor(ccc3(255, 255, 0));  //设置颜色

    CCMenuItemFont *loginItem = CCMenuItemFont::create("登录", this, menu_selector(
            HelloWorld::loginCallback));//添加文字按钮，点击实现缩放
    loginItem->setColor(ccc3(255, 0, 0));  //设置颜色

    //CCMenuItemFont::setFontSize(48);    //设置字号
    //CCMenuItemFont::setFontName("Marker Felt"); //设置字体
    //CCMenuItemFont *rechargeItem = CCMenuItemFont::create("充值", this, menu_selector(HelloWorld::rechargeCallback));//添加文字按钮，点击实现缩放
    //rechargeItem->setColor(ccc3(255, 0, 0));  //设置颜色
    //loginItem->setPosition(Vec2(origin.x + visibleSize.width / 2 - 80,
    //	origin.y + visibleSize.height/2));

    //font2->setSelectedIndex(1);    //设置默认显示，从零算起（此为off）
    CCMenu *newmenu = CCMenu::create(initItem, loginItem, NULL);  // 此步很关键，否则只是菜单项，但不能点击
    newmenu->setPosition(Vec2(origin.x + visibleSize.width / 2,
                              origin.y + visibleSize.height / 2 + 40));
    newmenu->alignItemsHorizontally();     //设置为横排排列
    newmenu->alignItemsHorizontallyWithPadding(40);//指定间隔
    this->addChild(newmenu, 2);

    CCMenuItemFont *rechargeItem = CCMenuItemFont::create("支付", this,
                                                          menu_selector(
                                                                  HelloWorld::rechargeCallback));   //添加选择按钮，点击实现on与off之间切换
    rechargeItem->setColor(ccc3(255, 0, 0));

    //CCMenuItemFont::setFontSize(48);    //设置字号
    //CCMenuItemFont::setFontName("Marker Felt"); //设置字体
    //CCMenuItemFont *rechargeItem = CCMenuItemFont::create("充值", this, menu_selector(HelloWorld::rechargeCallback));//添加文字按钮，点击实现缩放
    //rechargeItem->setColor(ccc3(255, 0, 0));  //设置颜色
    //loginItem->setPosition(Vec2(origin.x + visibleSize.width / 2 - 80,
    //	origin.y + visibleSize.height/2));
    CCMenuItemFont *logoutItem = CCMenuItemFont::create("注销", this,
                                                        menu_selector(
                                                                HelloWorld::logoutCallback));   //添加选择按钮，点击实现on与off之间切换
    logoutItem->setColor(ccc3(255, 0, 0));
    //font2->setSelectedIndex(1);    //设置默认显示，从零算起（此为off）
    CCMenu *newmenu1 = CCMenu::create(rechargeItem, logoutItem, NULL);  // 此步很关键，否则只是菜单项，但不能点击
    //newmenu->setPosition(Vec2(origin.x + visibleSize.width/2 - 80,
    //origin.y + visibleSize.height/2));
    newmenu1->setPosition(Vec2(origin.x + visibleSize.width / 2,
                               origin.y + visibleSize.height / 2 - 40));
    newmenu1->alignItemsHorizontally();     //设置为竖排排列
    newmenu1->alignItemsHorizontallyWithPadding(40);//指定间隔
    this->addChild(newmenu1, 2);
    return true;
}

//-------------------------------------------------初始化start----------------------------------------------------------------
void HelloWorld::initCallback(CCObject *pSender) {
    //初始化SDK
#if(CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
    JniMethodInfo info;
    //拿到activity
    //其中org/cocos2dx/cpp/为游戏包名
    bool havaActivity = JniHelper::getStaticMethodInfo(info, "org/cocos2dx/cpp/AppActivity",
                                                       "getActivity", "()Ljava/lang/Object;");
    jobject activity;//用于存放返回的对象
    if (havaActivity) {
        activity = info.env->CallStaticObjectMethod(info.classID,
                                                    info.methodID);//调用getObj函数，返回一个对象
    }
    //	判断org/cocos2dx/cpp/AppActivity.java中是否存在init非静态函数
    bool haveInit = JniHelper::getMethodInfo(info, "org/cocos2dx/cpp/AppActivity", "init",
                                             "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V");
    if (haveInit) {
        // 第一个参数和第二个参数：渠道id和渠道名称，一般联运不会特殊要求，这里填写固定值“0”和“自然注册”即可
        //第三、第四、第五个参数分别为： 游戏id、游戏名称、游戏appid，一般联运会要求填写对应游戏的真实参数以方便在联运后台区分对接是否成功
        // 第六、第七个参数：访问秘钥和联运SDK服务器地址联运提供
        jobject para1 = info.env->NewStringUTF("0");
        jobject para2 = info.env->NewStringUTF("自然注册");
        jobject para3 = info.env->NewStringUTF("56");
        jobject para4 = info.env->NewStringUTF("宠物小精灵(安卓版)");
        jobject para5 = info.env->NewStringUTF("9154EF06B9EEEA717");
        jobject para6 = info.env->NewStringUTF("CgsPEgsLEg8LCg==");
        jobject para7 = info.env->NewStringUTF("http://demo.vlcms.com/sdk.php/");
        info.env->CallVoidMethod(activity, info.methodID, para1, para2, para3, para4, para5, para6,
                                 para7);
    }
#endif

    CCLOG("init button clicked");
}
//-------------------------------------------------初始化end----------------------------------------------------------------

//-------------------------------------------------登录start----------------------------------------------------------------
void HelloWorld::loginCallback(CCObject *pSender) {
    CCLOG("login button clicked");
    //登录
#if(CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
    JniMethodInfo info;
    bool havaActivity = JniHelper::getStaticMethodInfo(info, "org/cocos2dx/cpp/AppActivity",
                                                       "getActivity", "()Ljava/lang/Object;");
    jobject activity;//用于存放返回的对象
    if (havaActivity) {
        activity = info.env->CallStaticObjectMethod(info.classID,
                                                    info.methodID);//调用getObj函数，返回一个对象
    }
    bool havaStartLogin = JniHelper::getMethodInfo(info, "org/cocos2dx/cpp/AppActivity",
                                                   "startLogin", "()V");
    if (havaStartLogin) {
        info.env->CallVoidMethod(activity, info.methodID);

    }
#endif

}
//-------------------------------------------------登录end----------------------------------------------------------------

//-------------------------------------------------充值start----------------------------------------------------------------
void HelloWorld::rechargeCallback(CCObject *pSender) {
    CCLOG("recharge button clicked");
    //充值
#if(CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
    JniMethodInfo info;
    //拿到activity
    bool havaActivity = JniHelper::getStaticMethodInfo(info, "org/cocos2dx/cpp/AppActivity",
                                                       "getActivity", "()Ljava/lang/Object;");
    jobject activity;//用于存放返回的对象
    if (havaActivity) {
        log("find method getActivity");
        activity = info.env->CallStaticObjectMethod(info.classID,
                                                    info.methodID);//调用getObj函数，返回一个对象
    }
    bool havePay = JniHelper::getMethodInfo(info, "org/cocos2dx/cpp/AppActivity", "pay",
                                            "(Ljava/lang/String;Ljava/lang/String;ILjava/lang/String;)V");
    if (havePay) {
		//第一个参数：物品名称， 第二个参数：物品描述， 第三个参数：商品价格（单位分）， 第四个参数：用于确认交易给玩家发送商品
        jobject para1 = info.env->NewStringUTF("灭世者的死亡之帽");
        jobject para2 = info.env->NewStringUTF(
                "灭世者的死亡之帽，是著名竞技类游戏《英雄联盟》中游戏道具。它可以提供大量的法术强度和额外的百分比法强，是暴力型法师、追求极限法强必备的装备，也是联盟里最热门的装备之一");
        //jint para3 = 1;
        jobject para4 = info.env->NewStringUTF("这里是透传参数");
        info.env->CallVoidMethod(activity, info.methodID, para1, para2, 1, para4);
    }
#endif
}
//java回调c++部分，支付结果,登录结果回调
extern "C"
{
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
//支付结果
void
Java_org_cocos2dx_cpp_AppActivity_returnPayResult(JNIEnv *env, jobject thiz, jstring payResult) {
    //"0" 支付成功 ,"1" 支付宝支付正在确认(可以当做支付成功), "2"支付宝支付未获取到支付结果 ,其它为支付失败
    const char *mPayResult = env->GetStringUTFChars(payResult, NULL);
    log("支付结果: %s ", mPayResult);
}
//登录结果
void Java_org_cocos2dx_cpp_AppActivity_returnLoginResult(JNIEnv *env, jobject thiz, jstring userId,
                                                         jstring token) {
    const char *mUserId = env->GetStringUTFChars(userId, NULL);
    const char *mToken = env->GetStringUTFChars(token, NULL);
    if (strlen(mUserId) == 0 || strlen(mToken) == 0) {
        log("登录失败");
    } else {
        //登录成功
        log("用户userid: %s", mUserId);
        log("用户token: %s", mToken);
    }
}

//防沉迷结果回调
void
Java_org_cocos2dx_cpp_AppActivity_returnAntiAddictionResult(JNIEnv *env, jobject thiz, jstring antiAddictionResult) {
    //"1" 第一次到时通知 ,"2" 第二次到时通知, "3"时间到，停止计时
    const char *mAntiAddictionResult = env->GetStringUTFChars(antiAddictionResult, NULL);
    log("防沉迷回调: %s ", mAntiAddictionResult);
}
#endif
}
//-------------------------------------------------充值end----------------------------------------------------------------

//-------------------------------------------------注销start----------------------------------------------------------------
void HelloWorld::logoutCallback(CCObject *pSender) {
    CCLOG("louout button clicked");
    //注销
#if(CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
    JniMethodInfo info;
    //拿到activity
    bool havaActivity = JniHelper::getStaticMethodInfo(info, "org/cocos2dx/cpp/AppActivity",
                                                       "getActivity", "()Ljava/lang/Object;");
    jobject activity;//用于存放返回的对象
    if (havaActivity) {
        activity = info.env->CallStaticObjectMethod(info.classID,
                                                    info.methodID);//调用getObj函数，返回一个对象
    }
    bool havaLogout = JniHelper::getMethodInfo(info, "org/cocos2dx/cpp/AppActivity", "logout",
                                               "()V");
    if (havaLogout) {

        info.env->CallVoidMethod(activity, info.methodID);
    }
#endif
}
//-------------------------------------------------注销end----------------------------------------------------------------

void HelloWorld::menuCloseCallback(Ref *pSender) {
    //Close the cocos2d-x game scene and quit the application
    Director::getInstance()->end();
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
    exit(0);
#endif

    /*To navigate back to native iOS screen(if present) without quitting the application  ,do not use Director::getInstance()->end() and exit(0) as given above,instead trigger a custom event created in RootViewController.mm as below*/

    //EventCustom customEndEvent("game_scene_close_event");
    //_eventDispatcher->dispatchEvent(&customEndEvent);


}
